package algorithm;

import java.util.concurrent.atomic.AtomicInteger;

public class T01114 {

    public static void main(String[] args) throws InterruptedException {
        int[] arr = {1, 2, 3};
        Foo foo = new Foo();
        Runnable[] tasks = new Runnable[] {
                () -> {
                    try {
                        foo.first(() -> {
                            System.out.print("1");
                        });
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                },
                () -> {
                    try {
                        foo.second(() -> {
                            System.out.print("2");
                        });
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                },
                () -> {
                    try {
                        foo.third(() -> {
                            System.out.print("3");
                        });
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
        };
        new Thread(tasks[arr[0] - 1]).start();// A
        new Thread(tasks[arr[1] - 1]).start();// B
        new Thread(tasks[arr[2] - 1]).start();// C
    }

    static class Foo {

        private volatile int state = 0;

        public Foo() {

        }

        public void first(Runnable printFirst) throws InterruptedException {
            printFirst.run();
            state = 1;
        }

        public void second(Runnable printSecond) throws InterruptedException {
            while(state != 1);
            printSecond.run();
            state = 2;
        }

        public void third(Runnable printThird) throws InterruptedException {
            while(state != 2);
            printThird.run();
        }
    }
}
